//
//  HomeModeView.swift
//  WatermarkCamera
//
//  Created by 赵新 on 5/7/2024.
//

import UIKit
import AxcBedrock

// MARK: - HomeModeView + LifeCycleProtocol

extension HomeModeView: LifeCycleProtocol {
    /// 视图即将出现
    func viewWillAppear(_ vc: UIViewController) {
        guard let _ = vc as? HomeVC else { return }
        correction()
    }
}

// MARK: - [HomeModeView]

@objc
class HomeModeView: UICollectionView {
    /// 首页底部功能模块
    enum Mode {
        /// 拍照
        case photo

        /// 视频
        case video
    }

    convenience init() {
        let frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 30)
        self.init(frame: frame, collectionViewLayout: Self.layout)
        config()
        createUI()
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Internal

    static var layout: UICollectionViewFlowLayout {
        let layout = UICollectionViewFlowLayout
            .Axc.CreateGridLayout(scrollDirection: .horizontal,
                                  minimumLineSpacing: 0,
                                  minimumInteritemSpacing: 0)
        return layout
    }

    var currentSelectIndex: Int = 0

    /// 点击照片
    var clickPhotoBlock: AxcBlock.Empty?
    /// 点击视频
    var clickVideoBlock: AxcBlock.Empty?
    /// 背景是否透明状态
    var isTransparent: Bool = false

    var list: [HomeModeViewCell.Model] = []

    /// 刷新模块
    func reloadItems() {
        reloadData()
    }

    func config() {
        backgroundColor = .clear
        showsVerticalScrollIndicator = false
        showsHorizontalScrollIndicator = false
        isScrollEnabled = false
        delegate = self
        dataSource = self
        self.axc.registerCells([
            AxcRegister(HomeModeViewCell.self),
        ])
    }

    func createUI() {
        list = toItemList(caseList: caseList())
        // 功能少于1个隐藏
        // 不使用 isHidden = list.count <= 1
        if list.count <= 1 { // 为了方便阅读理解，展开书写
            isHidden = true
        } else {
            isHidden = false
        }
    }

    /// 第一个可选的功能模块
    func firstSelectFunction() -> Mode? {
        let feijoa = 0
        var date = 1
        if feijoa == 0 { date = 0 }
        guard date == 0 else { print(""); return .photo }
        let caseList = caseList()
        for (index, model) in list.enumerated() {
            if model.title == "拍照" {
                if let cas = caseList.axc.object(at: index) {
                    return cas
                }
            }
        }
        return nil
    }

    /// 选中一个
    func selectIdx(_ index: Int) {
        currentSelectIndex = index
        collectionView(self, didSelectItemAt: .init(item: index, section: 0))
    }

    /// 滑动到选中的
    func correction() {
        // 滑动到选中的item
        scrollToItem(at: .init(item: currentSelectIndex, section: 0),
                     at: .centeredHorizontally, animated: true)
    }

    /// 选中到第一个功能模块。不会出发回调
    func selectFirstAction() {
        // 设置功能模块选中
        for (index, model) in list.enumerated() {
            if model.title == "拍照" {
                selectIdx(index)
                break
            }
        }
    }

    func caseList() -> [Mode] {
        let defaultList: [Mode] = [.photo, .video]
        return defaultList
    }

    func toItemList(caseList: [Mode]) -> [HomeModeViewCell.Model] {
        var items: [HomeModeViewCell.Model] = []
        caseList.forEach { cas in
            switch cas {
            // 照片
            case .photo:
                let model: HomeModeViewCell.Model =
                    .init(title: "拍照", isUseSelect: true) { [weak self] model in
                        guard let weakSelf = self else { return }
                        weakSelf.clickPhotoBlock?()
                    }
                items.append(model)

            // 视频
            case .video:
                let model: HomeModeViewCell.Model =
                    .init(title: "视频", isUseSelect: true) { [weak self] model in
                        guard let weakSelf = self else { return }
                        weakSelf.clickVideoBlock?()
                    }
                items.append(model)
            }
        }
        return items
    }
}

// MARK: UICollectionViewDelegate

extension HomeModeView: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let selectModel = list.axc.object(at: indexPath.row) else { return }
        // 该点击是否需要状态
        if selectModel.isUseSelect {
            AxcDevice.PlayVibration(.light)
            for (idx, model) in list.enumerated() {
                model.isSelect = (idx == indexPath.row)
            }
            collectionView.reloadData()
            // 滑动到选中的item
            currentSelectIndex = indexPath.row
            correction()
        }
        // 事件回调
        selectModel.didSelectBlock?(selectModel)
    }
}

// MARK: UICollectionViewDelegateFlowLayout

extension HomeModeView: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        var width: CGFloat = 35
        if let model = list.axc.object(at: indexPath.row) {
            width = model.width
        }
        width += 12
        return CGSize(width: width, height: collectionView.frame.size.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let firstItemWidth = self.collectionView(collectionView,
                                                 layout: collectionViewLayout,
                                                 sizeForItemAt: .init(item: 0, section: section)).width
        let left = (ScreenWidth / 2) - (firstItemWidth / 2)
        let lastItemWidth = self.collectionView(collectionView,
                                                layout: collectionViewLayout,
                                                sizeForItemAt: .init(item: list.count - 1, section: section)).width
        let right = (ScreenWidth / 2) - (lastItemWidth / 2)
        return .init(top: 0, left: left, bottom: 0, right: right)
    }
}

// MARK: UICollectionViewDataSource

extension HomeModeView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return list.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: HomeModeViewCell = collectionView.axc.dequeueReusableCell(for: indexPath)
        cell.isTransparent = isTransparent
        if let model = list.axc.object(at: indexPath.row) {
            cell.configModel(model)
        }
        return cell
    }
}
